<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-calendar"></i>
                    产品列表{{ cropImg }}
                </el-breadcrumb-item>
                <el-breadcrumb-item>新增产品</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="form-box">
                <el-form ref="form" :model="form" label-width="98px">
                    <el-form-item label="产品名称">
                        <el-input v-model="form.name"></el-input>
                    </el-form-item>
                    <el-form-item label="产品简介">
                        <el-input type="textarea" rows="5" v-model="form.desc"></el-input>
                    </el-form-item>


                    <el-form-item label="选择公司">
                        <el-select v-model="form.region" placeholder="请选择">
                            <el-option
                                v-for="(item, index) in getCompanyData"
                                :key="index"
                                :label="item.value"
                                :value="item.id"
                            ></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="产品资源类型">
                        <el-radio-group v-model="form.resource">
                            <el-radio key="0" label="0">图片</el-radio>
                            <el-radio key="1" label="1">视频</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="产品图片" v-if="form.resource == 0">
                       
                        <el-upload
                            class="upload"
                            :action="$myUrl.BASEURL + 'system/resourceFileUpload'"
                            :show-file-list="false"
                            :on-success="uploadSuccess"
                            :onError="uploadError"
                            :before-upload="beforImgUpload"
                            :data="titleImg"
                        >
                            <img v-if="imgUrl" :src="$myUrl.IMGURL + imgUrl" class="avatar" />
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </el-form-item>

                    <!-- ------------------------------视频上传--------------------------beforVideoUpload------ -->
                    <el-form-item label="产品视频"  v-else-if="form.resource == 1">
                          <el-upload
                        class="upload-demo"
                        drag
                        :action="$myUrl.BASEURL + 'system/resourceFileUpload'"
                        multiple
                        :on-success="uploadSuccess"
                        :onError="uploadError"
                        :before-upload="beforVideoUpload"
                        :data="titleImg"
                    >
                        <video :src="$myUrl.BASEURL + 'resource/' + this.imgUrl" controls v-if="this.imgUrl"></video>
                        <div v-else>
                            <i class="el-icon-upload"></i>
                            <div class="el-upload__text">
                                将文件拖到此处，或
                                <em>点击上传</em>
                            </div>
                        </div>

                        <div class="el-upload__tip" slot="tip">只能上传视频文件</div>
                    </el-upload>
                    </el-form-item>

                    <!-- <el-form-item label="是否推荐">
                        <el-switch v-model="form.delivery"></el-switch>
                    </el-form-item>-->
                    <el-form-item label="权重值" v-if="false">
                        <el-input v-model="form.name" placeholder="权重值越大，内容越排在前面"></el-input>
                    </el-form-item>
                    <br />
                    <el-form-item label="选择产品状态">
                        <el-select v-model="productStatus" placeholder="产品状态">
                            <el-option label="预备中" value="0"></el-option>
                            <el-option label="显示中" value="1"></el-option>
                            <el-option label="已下架" value="2"></el-option>
                        </el-select>
                    </el-form-item>


                    <!-- -------------------------------------------------编辑器测试--------------------------------------- -->
                    <el-form-item label="内容" style="width: 1100px" :toolbars="toolbars">
                        <div class="container">
                            <mavon-editor v-model="content" ref="md" @change="change" style="min-height: 600px" />
                            <!-- <el-button class="editor-btn" type="primary" @click="submit">提交</el-button> -->
                        </div>
                    </el-form-item>

                    <div v-for="(it, index) in textImgChoiseList" :key="index">
                        <el-form-item label="富文本图片" style="width: 1215px">
                            <el-radio-group v-model="linkSkipList[index].linkSkipType">
                                <el-radio
                                    @change="changeTextRadio($event, index)"
                                    v-for="item in it"
                                    :key="item.labelId"
                                    :label="item.labelId"
                                >
                                    {{ item.label }}
                                </el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="选择会展" v-if="linkSkipList[index].linkSkipType === 1">
                            <sele-search
                                @item-click="changeSeleSearch($event, index, 1)"
                                :itemlist="itemlist"
                                :placeholder="placeholder"
                                :nodatatext="nodatatext"
                            ></sele-search>
                        </el-form-item>
                        <el-form-item
                            label="选择个人页"
                            @item-click="changeSeleSearch($event, index, 2)"
                            v-if="linkSkipList[index].linkSkipType === 2"
                        >
                            <sele-search :itemlist="itemlist" :placeholder="placeholder" :nodatatext="nodatatext"></sele-search>
                        </el-form-item>
                        <el-form-item label="选择公司页" v-if="linkSkipList[index].linkSkipType === 3">
                            <el-cascader :options="options3" clearable @change="changeCascader($event, index, 3)"></el-cascader>
                        </el-form-item>
                        <el-form-item label="选择匠心人" style="500px" v-if="linkSkipList[index].linkSkipType === 4">
                            <el-cascader :options="options2" @change="changeCascader($event, index, 4)" clearable></el-cascader>
                        </el-form-item>
                        <el-form-item label="选择实景页" v-if="linkSkipList[index].linkSkipType === 5">
                            <el-cascader :options="options2" clearable @change="changeCascader($event, index, 5)"></el-cascader>
                        </el-form-item>
                        <el-form-item label="选择产品列表页" v-if="linkSkipList[index].linkSkipType === 6">
                            <el-cascader :options="options2" clearable @change="changeCascader($event, index, 6)"></el-cascader>
                        </el-form-item>
                        <el-form-item label="选择产品详情页" v-if="linkSkipList[index].linkSkipType === 7">
                            <el-cascader :options="options2" clearable @change="changeCascader($event, index, 7)"></el-cascader>
                        </el-form-item>
                    </div>

                    <el-form-item>
                        <el-button type="primary" @click="onSubmit">表单提交</el-button>
                        <el-button>取消</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>
    </div>
</template>

<script>
import axios from 'axios';
import VueCropper from 'vue-cropperjs';
import seleSearch from '../common/sele-search';
import { mavonEditor } from 'mavon-editor';
import 'mavon-editor/dist/css/index.css';
//import { getRichText } from '../../api/company.js';
import data from './data.js';
import { log } from 'util';
export default {
    name: 'product',
    components: {
        VueCropper,
        seleSearch,
        mavonEditor
    },
    // imgUrl
    data() {
        return {
             toolbars: {
},
            productId: '',
            productDetailData: '',
            // 产品状态
            productStatus: '',
            // 图片路径
            imgUrl: '',
            // 上傳接口參數
            titleImg: {
                fileGroup: 'product',
                fileidentName: 'productResource'
            },
            defaultLength: '',
            defaultObj: {
                linkSkipType: '',
                oneRelevantId: '',
                twoRelevantId: '',
                threeRelevantId: ''
            },
            linkSkipList: [],
            textImgChoiseList: [],
            content: '',
            html: '',
            placeholder: '请选取',
            nodatatext: '',
            form: {
                name: '',
                region: '',
                date1: '',
                date2: '',
                delivery: true,
                type: ['步步高'],
                resource: '小天才',
                desc: '',
                options: []
            },
            dialogVisible: false,
            // defaultSrc: require('../../assets/img/img.jpg'),
            fileList: [],
            imgSrc: '',
            radio: 0,
            textareaImgLen: 0,
            getCompanyData: []
        };
    },
    created() {
        this.cropImg = this.defaultSrc;
        this.getCompany();
        // this.productId = this.$route.query.productId;
        // console.log();
        this.form.name = '';
        this.form.desc = '';
        // 简介
        this.form.desc = '';
        // 公司ID
        this.productDetailData.companyId;
        // 图片或视频
        this.productDetailData.productResourceType;
        // 产品状态
        this.productStatus = '';
        // 富文本
        this.content = '';
        this.getProductDetail();
    },
    mounted() {},
    methods: {
        // 获取编辑数据
        getProductDetail() {
            axios.get(this.$myUrl.BASEURL + 'product/getProduct?productId=' + this.$route.query.productId).then((res) => {
                console.log('获取编辑数据', res.data.data);
                this.productDetailData = res.data.data;
                this.form.name = this.productDetailData.productName;
                this.form.desc = this.productDetailData.productDetailIntro;
                // 简介
                this.form.desc = this.productDetailData.productIntroduce;
                // 公司ID
                this.form.region = this.productDetailData.companyId;
                // 图片或视频状态
                this.form.resource =  this.productDetailData.productResourceType;
                // 图片或视频
                 this.imgUrl = this.productDetailData.productResource
                // 产品状态
                this.productStatus = this.productDetailData.productStatus;
                // 富文本
                this.content = this.productDetailData.richText;
            });
        },
        // 上传文件方法
        uploadSuccess(response, file, fileList) {
            console.log('上传文件', response);
            console.log('file', file);
            console.log('fileList', fileList);
            this.imgUrl = response.data.relativePath;
            // console.log(this.imgUrl);
        },
        // 上传错误
        uploadError() {
            console.log('上传失败，请重试！');
        },
        beforImgUpload(file) {
            console.log(file.type);
            const isJPG = file.type === 'image/jpeg' || file.type ===  'image/png';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
                this.$message.error('只能是上传 JPG/PNG 格式图片!');
            }
            if (!isLt2M) {
                this.$message.error('上传图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        },
        beforVideoUpload(file) {
            console.log('视频', file);
        },
        getCompany() {
            axios.get(this.$myUrl.BASEURL + 'company/getCompanyBasicList').then((res) => {
                this.getCompanyData = res.data.data;
            });
        },
        changeCascader(e, index, type) {
            if (type === 3 || type === 4 || type === 5) {
                //console.log(e)
                this.linkSkipList[index].oneRelevantId = e[0];
                this.linkSkipList[index].twoRelevantId = e[1];
            }
            if (type === 6 || type === 7) {
                //console.log(e)
                this.linkSkipList[index].oneRelevantId = e[0];
                this.linkSkipList[index].twoRelevantId = e[1];
                this.linkSkipList[index].threeRelevantId = e[2];
            }
        },
        change(value, render) {
            // render 为 markdown 解析后的结果
            this.html = render;
        },
        changeRadio(e) {
            //console.log(e);
            this.radio = e;
        },
        changeTextRadio(e, index) {
            // //console.log(e)
            // //console.log(index)
            this.linkSkipList[index].linkSkipType = e;
        },
        changeSeleSearch(e, index, type) {
            this.linkSkipList[index].oneRelevantId = e;
            //console.log(e)
            //console.log(index)
        },

        // 表单提交按钮
        onSubmit() {
            console.log('-------------');
            console.log(this.form.region);
            console.log(this.form.desc);
            console.log(this.form.name);
            console.log(this.html);
            if (!this.$route.query.productId) {
                axios
                    .post(this.$myUrl.BASEURL + 'product/addProduct', {
                        companyId: this.form.region,
                        productIntroduce: this.form.desc,
                        productName: this.form.name,
                        productResourceType: this.form.resource,
                        productStatus: this.productStatus,
                        productResource: this.imgUrl,
                        richText: this.html
                    })
                    .then((res) => {
                        console.log(res);
                        if (res.data.code == 200) {
                            this.$message.success('提交成功！');
                            this.$router.push('/product-list');
                        } else {
                            this.$message.success(res.data.msg);
                        }
                    })
                    .catch(() => {
                        this.$message.success('提交失败！');
                    });
            } else {
                axios
                    .put(this.$myUrl.BASEURL + 'product/updateProduct', {
                        companyId: this.form.region,
                        productIntroduce: this.form.desc,
                        productName: this.form.name,
                        productResourceType: this.form.resource,
                        productStatus: this.productStatus,
                        productResource: this.imgUrl,
                        richText: this.html,
                        id: this.$route.query.productId
                    })
                    .then((res) => {
                        // console.log(res);
                        if (res.data.code == 200) {
                            this.$message.success('修改成功');
                            this.$router.push('/product-list');
                        } else {
                            this.$message.error(res.data.msg);
                        }
                    });
            }
        },
        dataURLtoFile(dataurl, filename) {
            let arr = dataurl.split(',');
            let mime = arr[0].match(/:(.*?);/)[1];
            let bstr = atob(arr[1]);
            let len = bstr.length;
            let u8arr = new Uint8Array(len);
            while (len--) {
                u8arr[len] = bstr.charCodeAt(len);
            }
            return new File([u8arr], filename, { type: mime });
        },

        setImage(e) {
            console.log('改变');
            console.log(e);
            const file = e.target.files[0];
            //console.log(file)
            if (!file.type.includes('image/')) {
                return;
            }
            const reader = new FileReader();
            reader.onload = (event) => {
                // console.log(event);
                this.dialogVisible = true;
                this.imgSrc = event.target.result;
                // console.log('this.imgSrc',this.imgSrc)
                let exStr = this.imgSrc;
                const Base64 = require('js-base64').Base64;
                exStr = Base64.encode('base64');
                console.log(exStr);
                // console.log('0000000000', this.dataURLtoFile(this.imgSrc, file.name));
                this.$refs.cropper && this.$refs.cropper.replace(event.target.result);
            };

            console.log(reader.readAsDataURL(file));
        },
        cropImage() {
            this.cropImg = this.$refs.cropper.getCroppedCanvas().toDataURL();
        },
        cancelCrop() {
            this.dialogVisible = false;
            this.cropImg = this.defaultSrc;
        },
        imageuploaded(res) {
            //console.log(res);
        },
        handleError() {
            this.$notify.error({
                title: '上传失败',
                message: '图片上传接口上传失败，可更改为自己的服务器接口'
            });
        }
    }
};
</script>
<style scoped>
.editor-btn {
    margin-top: 20px;
}
/* .el-form-item__content{
    width: 1200px !important;
} */
.content-title {
    font-weight: 400;
    line-height: 50px;
    margin: 10px 0;
    font-size: 22px;
    color: #1f2f3d;
}
.pre-img {
    width: 100px;
    height: 100px;
    background: #f8f8f8;
    border: 1px solid #eee;
    border-radius: 5px;
}
.crop-demo {
    display: flex;
    align-items: flex-end;
}
.crop-demo-btn {
    position: relative;
    width: 100px;
    height: 40px;
    line-height: 40px;
    padding: 0 20px;
    margin-left: 30px;
    background-color: #409eff;
    color: #fff;
    font-size: 14px;
    border-radius: 4px;
    box-sizing: border-box;
}
.crop-input {
    position: absolute;
    width: 100px;
    height: 40px;
    left: 0;
    top: 0;
    opacity: 0;
    cursor: pointer;
}
video {
    width: 100%;
    height: 100%;
}
</style>